package com.sec.etech.employeesync.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeMainWorkExperience;
import com.sec.etech.employeesync.entity.OrgEmployeeZCompany;
import com.sec.etech.employeesync.mapper.OrgEmployeeMainWorkExperienceMapper;
import com.sec.etech.employeesync.mapper.OrgEmployeeZCompanyMapper;
import com.sec.etech.employeesync.service.MainWorkExperienceService;
import com.sec.etech.sys.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openbpm.org.api.model.IUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MainWorkExperienceHandler {

    @Resource
    private OrgEmployeeMainWorkExperienceMapper mainWorkExperienceMapper;
    @Resource
    private OrgEmployeeZCompanyMapper companyMapper;
    @Autowired
    private MainWorkExperienceService mainWorkExperienceService;

    private final Map<String, Long> companyMap = new HashMap<>();
    private final Map<Long, List<OrgEmployeeMainWorkExperience>> employeeExperienceMap = new HashMap<>();

    public void handleMainWorkExperience(Long employeeId, JSONArray mainWorkExperienceData) {
        // 删除现有的主业经历记录
        mainWorkExperienceMapper.delete(
                new QueryWrapper<OrgEmployeeMainWorkExperience>()
                        .eq("employeeid", employeeId)
                        .eq("origin", 1)
        );

        // 插入新的主业经历记录
        for (int i = 0; i < mainWorkExperienceData.size(); i++) {
            JSONObject experienceData = mainWorkExperienceData.getJSONObject(i);
            OrgEmployeeMainWorkExperience experience = convertToMainWorkExperience(employeeId, experienceData);
            mainWorkExperienceMapper.insert(experience);
        }

        log.info("更新员工主业经历: employeeId = {}, 记录数 = {}", employeeId, mainWorkExperienceData.size());
    }

    public OrgEmployeeMainWorkExperience convertToMainWorkExperience(Long employeeId, JSONObject experienceData) {
        OrgEmployeeMainWorkExperience experience = new OrgEmployeeMainWorkExperience();
        experience.setEmployeeid(employeeId);
        experience.setOrigin(1);
        experience.setStartDate(parseDate(experienceData.getString("BEGDA")));
        experience.setEndDate(parseDate(experienceData.getString("ENDDA")));
        experience.setActive(1);
        experience.setIsInGroup(1);

        // 公司
        String bukrs = experienceData.getString("BUKRS");
        if (StringUtils.isNotBlank(bukrs)) {
            experience.setCompanyId(companyMap.get(bukrs));
        }

        // 部门
        String orgtx = experienceData.getString("ORGTX");
        if (StringUtils.isNotBlank(orgtx)) {
            experience.setDepartment(orgtx);
        }

        // 岗位
        String plstx = experienceData.getString("PLSTX");
        if (StringUtils.isNotBlank(plstx)) {
            experience.setJobName(plstx);
        }

        return experience;
    }

    private Date parseDate(String dateString) {
        if (StringUtils.isBlank(dateString)) {
            return null;
        }
        try {
            return new SimpleDateFormat("yyyyMMdd").parse(dateString);
        } catch (ParseException e) {
            log.error("日期解析错误: {}", dateString, e);
            return null;
        }
    }

    public void insertMainWorkExperience(Long employeeId, JSONArray employeeMainWorkExperience, IUser iUser) {
        ContextUtil.setCurrentUser(iUser);

        List<OrgEmployeeMainWorkExperience> list = employeeMainWorkExperience.parallelStream()
                .map(obj -> (JSONObject) obj)
                .map(data -> convertToMainWorkExperience(employeeId, data))
                .collect(Collectors.toList());

        mainWorkExperienceService.saveBatch(list);
    }

    public void deleteMainWorkExperience(Long employeeId) {
        List<OrgEmployeeMainWorkExperience> list = mainWorkExperienceService.list(Wrappers.<OrgEmployeeMainWorkExperience>lambdaQuery()
                .eq(OrgEmployeeMainWorkExperience::getEmployeeid, employeeId)
                .eq(OrgEmployeeMainWorkExperience::getOrigin, 1)
        );

        if (!list.isEmpty()) {
            list.parallelStream()
                    .forEach(experience -> experience.setActive(0));
        }

        mainWorkExperienceService.updateBatchById(list);
    }

    public boolean checkIfExists(Long employeeId, JSONObject experienceData) {
        List<OrgEmployeeMainWorkExperience> employeeExperienceList = employeeExperienceMap.getOrDefault(employeeId, new ArrayList<>());

        return employeeExperienceList.parallelStream()
                .anyMatch(experience -> isExperienceMatch(experience, experienceData));
    }

    private boolean isExperienceMatch(OrgEmployeeMainWorkExperience experience, JSONObject experienceData) {
        Date startDate = experience.getStartDate();
        Date endDate = experience.getEndDate();
        Long companyId = experience.getCompanyId();
        String department = experience.getDepartment();
        String jobName = experience.getJobName();

        return dateEqual(startDate, parseDate(experienceData.getString("BEGDA")))
                && dateEqual(endDate, parseDate(experienceData.getString("ENDDA")))
                && longEqual(companyId, companyMap.get(experienceData.getString("BUKRS")))
                && stringEqual(department, experienceData.getString("ORGTX"))
                && stringEqual(jobName, experienceData.getString("PLSTX"));
    }

    public static boolean longEqual(Long num1, Long num2) {
        // 如果两个都是null，则相等
        if (num1 == null && num2 == null) {
            return true;
        }
        // 如果一个为null而另一个不为null，则不相等
        if (num1 == null || num2 == null) {
            return false;
        }
        // 两个都不为null，比较数值
        return num1.equals(num2);
    }


    public boolean dateEqual(Date date1, Date date2) {
        // 如果两个都是null，则相等
        if (date1 == null && date2 == null) {
            return true;
        }
        // 如果一个为null而另一个不为null，则不相等
        if (date1 == null || date2 == null) {
            return false;
        }
        // 两个都不为null，比较时间
        return date1.equals(date2);
    }

    public static boolean stringEqual(String str1, String str2) {
        // 使用 StringUtils.trimToNull() 方法处理字符串
        String trimmedStr1 = StringUtils.trimToNull(str1);
        String trimmedStr2 = StringUtils.trimToNull(str2);

        // 使用 equals() 方法比较字符串
        return trimmedStr1 == null ? trimmedStr2 == null : trimmedStr1.equals(trimmedStr2);
    }

    public void updateMainWorkExperience(OrgEmployeeMainWorkExperience employeeMainWorkExperience, OrgEmployeeMainWorkExperience existOrgEmployeeMainWorkExperience) {
        existOrgEmployeeMainWorkExperience.setDepartment(employeeMainWorkExperience.getDepartment());
        existOrgEmployeeMainWorkExperience.setJobName(employeeMainWorkExperience.getJobName());
//        existOrgEmployeeMainWorkExperience.setActive(1);


        mainWorkExperienceService.updateById(existOrgEmployeeMainWorkExperience);
    }

    public void initCompanyMap() {
        Map<String, Long> newMap = companyMapper.selectList(null)
                .parallelStream()
                .collect(Collectors.toMap(OrgEmployeeZCompany::getCode, OrgEmployeeZCompany::getCompanyId));

        companyMap.clear();
        companyMap.putAll(newMap);
    }


    public void initAllExperiences() {
        List<OrgEmployeeMainWorkExperience> allExperienceList = mainWorkExperienceMapper.selectList(Wrappers.<OrgEmployeeMainWorkExperience>lambdaQuery()
                .eq(OrgEmployeeMainWorkExperience::getOrigin, 1));

        Map<Long, List<OrgEmployeeMainWorkExperience>> tempMap = allExperienceList.parallelStream()
                .collect(Collectors.groupingBy(OrgEmployeeMainWorkExperience::getEmployeeid, Collectors.toList()));

        employeeExperienceMap.clear();
        employeeExperienceMap.putAll(tempMap);
    }
}
